interface tagObjType {
  title: string;
  child?: any[];
  level?: number;
  order?: any
}

export default function tocHelper(html: string) {
  let content = html;
  const tagCount = {
    h1: 0,
    h2: 0,
    h3: 0,
    h4: 0,
    h5: 0,
    h6: 0
  };

  let reg = /<(h[2|3|4|5|6])[^]*?>([^]*?)<\/\1>/g;
  let regATag = /<(a)[^]*?>([^]*?)<\/a>/g;

  try {
    const titleList: Array<tagObjType> = [];
    let title: RegExpExecArray | null;

    let lastTag: any = null;

    while ((title = reg.exec(content))) {
      const tag = title[1];
      const tagContent = title[2].replace(regATag, '').trim(); // 移除 anchor
      let order = '';
      let tagObj: tagObjType = {
        title: '',
        child: []
      };
      let level = 0;

      switch (tag) {
        case 'h2':
          tagCount.h2++;
          tagCount.h3 = 0;
          tagCount.h4 = 0;
          tagCount.h5 = 0;
          tagCount.h6 = 0;

          order = `${tagCount.h2}.`;
          level = 5;
          break;
        case 'h3':
          tagCount.h3++;
          tagCount.h4 = 0;
          tagCount.h5 = 0;
          tagCount.h6 = 0;

          order = `${tagCount.h2}.${tagCount.h3}.`;
          level = 4;
          break;
        case 'h4':
          tagCount.h4++;
          tagCount.h5 = 0;
          tagCount.h6 = 0;

          order = `${tagCount.h2}.${tagCount.h3}.${tagCount.h4}.`;
          level = 3;
          break;
        case 'h5':
          tagCount.h5++;
          tagCount.h6 = 0;

          order = `${tagCount.h2}.${tagCount.h3}.${tagCount.h4}.${tagCount.h5}.`;
          level = 2;
          break;
        case 'h6':
          tagCount.h6++;

          order = `${tagCount.h2}.${tagCount.h3}.${tagCount.h4}.${tagCount.h5}.${tagCount.h6}.`;
          level = 1;
          break;
      }
      tagObj = {
        title: `${tagContent}`,
        order: order,
        level,
        child: []
      };

      if (lastTag && lastTag.level > level) {
        lastTag.child.push(tagObj);
      } else {
        lastTag = tagObj;
        titleList.push(lastTag);
      }

      content = content.replace(title[0], '');
    }
    return titleList;
  } catch (error) {
    console.log('toc error', error);
  }
}
